package com.zhuiyun.project.api.memberUserManagement.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuiyun.project.api.caseImage.entity.CaseImage;
import com.zhuiyun.project.api.caseImage.mapper.CaseImageMapper;
import com.zhuiyun.project.api.coachmanagement.entity.CoachManagement;
import com.zhuiyun.project.api.dukacard.config.WebSocketServer;
import com.zhuiyun.project.api.memberTypeManagement.entity.MemberCardNumber;
import com.zhuiyun.project.api.memberTypeManagement.entity.MemberTypeManagement;
import com.zhuiyun.project.api.memberTypeManagement.mapper.MemberTypeMapper;
import com.zhuiyun.project.api.memberTypeManagement.model.MemberTypeManagementModel;
import com.zhuiyun.project.api.memberTypeManagement.model.MemberTypeModel;
import com.zhuiyun.project.api.memberTypeManagement.service.MemberTypeService;
import com.zhuiyun.project.api.memberUserManagement.entity.MemberUserManagement;
import com.zhuiyun.project.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.zhuiyun.project.api.memberUserManagement.model.MemberUserAndTypeModel;
import com.zhuiyun.project.api.memberUserManagement.model.MemberUserModel;
import com.zhuiyun.project.api.memberUserManagement.service.MemberUserManagementService;
import com.zhuiyun.project.api.membershipRelationships.entity.MembershipRelationships;
import com.zhuiyun.project.api.membershipRelationships.mapper.MembershipRelationshipsMapper;
import com.zhuiyun.project.api.reservation.mapper.ReservationMapper;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.mapper.SysUserMapper;
import com.zhuiyun.project.api.vipPlan.model.ActionListModel;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.UploadFileUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.LocalDate;

import java.util.Date;

/**
 * @ClassName MemberUserManagementServiceImpl
 * @Description TODO 会员用户管理业务层实现类
 * @Author WX
 * @Date 2023/11/3 8:36
 **/
@Service
public class MemberUserManagementServiceImpl implements MemberUserManagementService {

    @Autowired
    private MemberUserManagementMapper memberUserManagementMapper;

    @Autowired
    private MemberTypeMapper memberTypeMapper;

    @Autowired
    private MembershipRelationshipsMapper membershipRelationshipsMapper;

    @Autowired
    private CaseImageMapper caseImageMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * @Author WX
     * @Description 获取会员用户信息
     * @Date 2023/11/3 10:15
     * @Return
     * @param pageRequest memberUserModel
     */
    @Override
    public PageResult getMemberType(PageRequest pageRequest, MemberUserModel memberUserModel) {
        MybatisPageHelper.startPage(pageRequest);
        List<MemberUserAndTypeModel> memberUserAndTypeModelList = memberUserManagementMapper.getMemberType(memberUserModel);
        PageResult pageResult = MybatisPageHelper.getPageResult(memberUserAndTypeModelList);
        return pageResult;
    }

    /**
     * @Author wx
     * @Description 通过手机号查询用户信息
     * @Date 2023/11/6 11:28
     * @Return
     * @param memberUserAndTypeModel
     */
    @Override
    public CommonResult selectByPhone(MemberUserAndTypeModel memberUserAndTypeModel) {
        return CommonResult.ok(memberUserManagementMapper.selectByPhone(memberUserAndTypeModel));
    }

    /**
     * @Author wx
     * @Description 通过手机号查询用户信息
     * @Date 2023/11/6 11:28
     * @Return
     * @param
     */
    @Override
    public CommonResult selectByPhoneOnly(String phone) {
        return CommonResult.ok(memberUserManagementMapper.selectByPhoneOnly(phone));
    }

    /**
     * @Author wx
     * @Description 查询会员类型信息
     * @Date 2023/11/6 9:20
     * @Return
     */
    @Override
    public CommonResult getMemberList(String venueUniqueIdentifier) {
        return CommonResult.ok(memberTypeMapper.getMemberList(venueUniqueIdentifier));
    }

    /**
    * @Author wx
    * @Description 新增会员用户
    * @Date 2023/11/7 9:40
    * @Return
    * @param memberUserAndTypeModel MultipartFile
    */
    @Override
    public CommonResult addMember(MemberUserAndTypeModel memberUserAndTypeModel, MultipartFile file)  throws CommonException {
        // 获取当前时间的 LocalDate 对象
        LocalDate currentDate = LocalDate.now();
        if (ValidatorUtil.ValidationObject(memberUserAndTypeModel)) {
            memberUserAndTypeModel.setAenableStatus(0);
            // 判断用户身高是否存在
            if (memberUserAndTypeModel.getMemberUserHeight() == null){
                memberUserAndTypeModel.setMemberUserHeight(0);
            }
            // 判断用户体重是否存在
            if (memberUserAndTypeModel.getMemberUserWeight() == null){
                memberUserAndTypeModel.setMemberUserWeight(0.00);
            }
            if (memberUserAndTypeModel.getMemberUserWeight() ==0.00 && memberUserAndTypeModel.getMemberUserHeight() == 0 ){
                memberUserAndTypeModel.setMemberUserBodyFat(0.00);
            }else {
                double age;
                if (memberUserAndTypeModel.getMemberUserSex() ==1){
                    age=0.00;
                }else {
                    age=1.00;
                }
                double tizhon = memberUserAndTypeModel.getMemberUserWeight();
                double shengao = (double)memberUserAndTypeModel.getMemberUserHeight()/100;
                double bmi = tizhon/(shengao*shengao);
                // 计算体脂率
                memberUserAndTypeModel.setMemberUserBodyFat((1.2*bmi)+(0.23*(double)memberUserAndTypeModel.getMemberUserAge())-5.4-(10.8*age));
            }
            if (file == null) {
                return CommonResult.ok(EmErrorCode.FILE_EMPTY);
            } else {
                Integer s = Integer.valueOf(UploadFileUtils.uploadFile(file));
                if (s.equals("")) {
                    return CommonResult.ok(EmErrorCode.FILE_EMPTY);
                }
                memberUserAndTypeModel.setMemberUserPhoto(s);
                memberUserAndTypeModel.setCreateTime(new Date());
                memberUserAndTypeModel.setUpdateTime(new Date());
                // 查询是否已存在用户手机号
                List<MemberUserManagement> managementList = memberUserManagementMapper.selectByPhone(memberUserAndTypeModel);
                if (managementList.size() > 0) {
                    return CommonResult.ok("手机号已存在");
                } else {
                    int i = memberUserManagementMapper.addMemberUser(memberUserAndTypeModel);
                    if (i>0){
                        if (memberUserAndTypeModel.getServiceLife() != 0){
                            int serviceLife =memberUserAndTypeModel.getServiceLife();
                            // 添加 serviceLife 个月
                            LocalDate expirationDate = currentDate.plusMonths(serviceLife);

                            // 转换为 Date 对象
                            Date expirationTime = Date.from(expirationDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                            // 设置到期时间
                            memberUserAndTypeModel.setExpirationTime(expirationTime);
                        }else {
                            memberUserAndTypeModel.setExpirationTime(new Date());
                        }
                        if (memberUserAndTypeModel.getMemberType() == 1 && memberUserAndTypeModel.getAvailableTimes() ==null){
                            memberUserAndTypeModel.setAvailableTimes(0);
                        }
                        boolean b =membershipRelationshipsMapper.addMemberUserShip(memberUserAndTypeModel);
                        if (b){
                            return CommonResult.ok(EmErrorCode.SAVE_OK);
                        }else { 
                            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                        }
                    }else {
                        return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                    }
                }
            }
        }
        else {
            return CommonResult.ok("存在空内容");
        }
    }

    /**
     * @Author wx
     * @Description 根据id查询单个会员的数据
     * @Date 2023/11/7 8:29
     * @Return
     * @param id
     */
    @Override
    public MemberUserAndTypeModel getById(Integer id,String venueUniqueIdentifier) {
         MemberUserAndTypeModel memberUserAndTypeModel =memberUserManagementMapper.getById(id,venueUniqueIdentifier);
         if (memberUserAndTypeModel != null && memberUserAndTypeModel.getInvitationCode() != null && !memberUserAndTypeModel.getInvitationCode().equals("null")){
             String invitationCode =memberUserAndTypeModel.getInvitationCode();
             // 查询教练信息
             CoachManagement coachManagement =memberUserManagementMapper.getByInvitationCode(invitationCode,venueUniqueIdentifier);
             memberUserAndTypeModel.setCoachName(coachManagement.getCoachName()) ;
         }
         if (memberUserAndTypeModel.getExpirationTime() == null){
             return memberUserAndTypeModel;
         }else {
             // 获取 rcreateTime 和 expirationTime 字段的 Date 对象
             Date rcreateTimeDate = memberUserAndTypeModel.getRcreateTime();
             Date expirationTimeDate = memberUserAndTypeModel.getExpirationTime();

             // 将 Date 对象转换为 LocalDate 对象
             LocalDate rcreateTime = rcreateTimeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
             LocalDate expirationTime = expirationTimeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();


             // 计算两个日期之间的差异
             Period period = Period.between(rcreateTime, expirationTime);
             int diffMonths = period.getYears() * 12 + period.getMonths();
             memberUserAndTypeModel.setServiceLife(diffMonths);
             return memberUserAndTypeModel;
         }


    }

    /**
    * @Author wx
    * @Description 修改会员用户信息
    * @Date 2023/11/7 10:45
    * @Return 
    * @param memberUserAndTypeModel
    */
    
    @Override
    public CommonResult updateMemberById(MemberUserAndTypeModel memberUserAndTypeModel, MultipartFile file) throws CommonException{
        // 获取当前时间的 LocalDate 对象
        LocalDate currentDate = LocalDate.now();

        if (!ValidatorUtil.ValidationObject(memberUserAndTypeModel)) {
            return CommonResult.ok("存在空内容");
        }

        memberUserAndTypeModel.setAenableStatus(0);
        if (memberUserAndTypeModel.getMemberUserHeight() == null) {
            memberUserAndTypeModel.setMemberUserHeight(0);
        }
        if (memberUserAndTypeModel.getMemberUserWeight() == null) {
            memberUserAndTypeModel.setMemberUserWeight(0.00);
        }
        if (memberUserAndTypeModel.getMemberUserWeight() == 0.00 && memberUserAndTypeModel.getMemberUserHeight() == 0) {
            memberUserAndTypeModel.setMemberUserBodyFat(0.00);
        } else {
            double age = memberUserAndTypeModel.getMemberUserSex() == 1 ? 0.00 : 1.00;
            double tizhon = memberUserAndTypeModel.getMemberUserWeight();
            double shengao = (double) memberUserAndTypeModel.getMemberUserHeight() / 100;
            double bmi = tizhon / (shengao * shengao);
            memberUserAndTypeModel.setMemberUserBodyFat((1.2 * bmi) + (0.23 * (double) memberUserAndTypeModel.getMemberUserAge()) - 5.4 - (10.8 * age));
        }

        // 检查手机号是否已存在
        if (!checkPhoneNumberExists(memberUserAndTypeModel)) {
            return CommonResult.ok("手机号已存在");
        }

        Integer s = null;
        try {
            if (file != null) {
                s = Integer.valueOf(UploadFileUtils.uploadFile(file));
                if (s.equals("")) {
                    return CommonResult.ok(EmErrorCode.FILE_EMPTY);
                }
            }

            memberUserAndTypeModel.setMemberUserPhoto(s);
            memberUserAndTypeModel.setUpdateTime(new Date());

            int i = memberUserManagementMapper.updateMemberUser(memberUserAndTypeModel);
            if (i <= 0) {
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }

            if (memberUserAndTypeModel.getServiceLife() != 0) {
                // 添加 serviceLife 个月
                LocalDate expirationDate = currentDate.plusMonths(memberUserAndTypeModel.getServiceLife());

                // 转换为 Date 对象
                Date expirationTime = Date.from(expirationDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                // 设置到期时间
                memberUserAndTypeModel.setExpirationTime(expirationTime);
            } else {
                memberUserAndTypeModel.setExpirationTime(new Date());
            }

            boolean b = membershipRelationshipsMapper.updateMemberUserShip(memberUserAndTypeModel);
            if (b) {
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            } else {
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        } catch (NumberFormatException e) {
            return CommonResult.ok(EmErrorCode.FILE_EMPTY);
        }
    }

    private boolean checkPhoneNumberExists(MemberUserAndTypeModel memberUserAndTypeModel) {
        List<MemberUserManagement> managementList = memberUserManagementMapper.selectByPhone(memberUserAndTypeModel);
        if (managementList.size() > 1) {
            for (MemberUserManagement management : managementList) {
                if (management.getId() != memberUserAndTypeModel.getId()) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public CommonResult updateMemberByIds(MemberUserAndTypeModel memberUserAndTypeModel)  {
        return CommonResult.ok(memberUserManagementMapper.updateMemberUser(memberUserAndTypeModel));
    }

    /**
     * @Author wx
     * @Description 根据邀请码查询教练的数据
     * @Date 2023/11/7 8:29
     * @Return
     * @param invitationCode
     */
    @Override
    public CoachManagement getByInvitationCode(String invitationCode, String venueUniqueIdentifier) {
        CoachManagement coachManagement = memberUserManagementMapper.getByInvitationCode(invitationCode,venueUniqueIdentifier);
        return coachManagement;
    }

    /**
     * @Author wx
     * @Description 刷卡确认后条件判断删除任务
     * @Date 2023/12/3 18:51
     * @Return
     * @param venueUniqueIdentifier,memberUserPhone
     */
    @Override
    public CommonResult getByMemberUserPhone(String memberUserPhone, String venueUniqueIdentifier) {
        MemberUserManagement memberUserManagement = memberUserManagementMapper.selectByMemberUserPhone(memberUserPhone,venueUniqueIdentifier);
        Integer id =memberUserManagement.getId();
        String membershipCardNumber = memberUserManagement.getMembershipCardNumber();
        // 根据卡号查询刷卡记录
        MemberCardNumber memberCardNumber = memberUserManagementMapper.selectCardNumberByCard(membershipCardNumber,venueUniqueIdentifier);
        if (memberCardNumber == null){
            // 添加记录
            memberUserManagementMapper.addMemberCardNumber(membershipCardNumber,venueUniqueIdentifier);
        }else {
            LocalDate currentDate = LocalDate.now();

            // 从 memberCardNumber.getUpdateTime() 中获取日期，并转换为 LocalDate
            Date updateDate = memberCardNumber.getUpdateTime();
            Instant instant = updateDate.toInstant();
            LocalDate updateLocalDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

            // 判断日期是否是今天
            boolean isToday = updateLocalDate.isEqual(currentDate);

            if (isToday) {
                memberUserManagementMapper.addMemberCardNumberToday(membershipCardNumber,venueUniqueIdentifier);
            } else {
                memberUserManagementMapper.updateMemberCardNumberToday(membershipCardNumber,venueUniqueIdentifier);
            }
        }
        return CommonResult.ok(memberUserManagementMapper.deleteByMemberUserPhone(id));
    }

    /**
     * @Author wx
     * @Description 教练端查询会员信息
     * @Date 2023/12/12 9:57
     * @Return
     * @param id
     */
    @Override
    public CommonResult selectUserCase(String venueUniqueIdentifier, Integer id,String coachId) {
        return CommonResult.ok(memberUserManagementMapper.selectUserCase(venueUniqueIdentifier,id,coachId));
    }

    /**
     * @Author wx
     * @Description 查询用户案例图片
     * @Date 2023/12/12 10:21
     * @Return
     * @param id
     */
    @Override
    public CommonResult selectUserInfoImage(Integer id,Integer coachId) {
        QueryWrapper<CaseImage> caseImageQueryWrapper = new QueryWrapper<>();
        caseImageQueryWrapper.eq("user_id",id);
        caseImageQueryWrapper.eq("coach_id",coachId);
        caseImageQueryWrapper.select("DATE_FORMAT(create_time,'%Y-%m-%d') as createTime","action_image");
        List<CaseImage> caseImages = caseImageMapper.selectList(caseImageQueryWrapper);


//        LinkedHashSet<String> yearSet = new LinkedHashSet<>();
//        // 查询创建时间
//        List<CaseImage> caseImages = memberUserManagementMapper.selectUserInfoTime(id,coachId);
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        for (CaseImage c:caseImages){
//            Date createTime = c.getCreateTime();
//            String yearMonth = dateFormat.format(createTime);
//            yearSet.add(yearMonth);
//        }
//        for (String yearMonth : yearSet) {
//
//        }
        return CommonResult.ok(caseImages);
    }

    /**
     * @Author wx
     * @Description 查询场管名称
     * @Date 2023/12/13 8:51
     * @Return
     * @param venueUniqueIdentifier
     */
    @Override
    public CommonResult selectVenueName(String venueUniqueIdentifier) {
        SysUser sysUser = sysUserMapper.selectVenueName(venueUniqueIdentifier);
        String userName = sysUser.getUserName();
        return CommonResult.ok(userName);
    }

    /**
     * @Author wx
     * @Description 读卡回显信息
     * @Date 2023/12/22 9:03
     * @Return
     * @param venueUniqueIdentifier
     */
    @Override
    public CommonResult selectUserInfoByNumid(String venueUniqueIdentifier, String membershipCardNumber) {
        if (StringUtils.isNotEmpty(venueUniqueIdentifier) && StringUtils.isNotEmpty(membershipCardNumber)){
            MemberUserAndTypeModel byMembershipCardNumber = memberUserManagementMapper.getByMembershipCardNumber(venueUniqueIdentifier, membershipCardNumber);
            if (byMembershipCardNumber != null){
                // 判断教练邀请码是否拥有
                if (byMembershipCardNumber.getInvitationCode() != null && !byMembershipCardNumber.getInvitationCode().equals("null")){
                    String invitationCode = byMembershipCardNumber.getInvitationCode();
                    // 查询教练信息
                    CoachManagement coachManagement = memberUserManagementMapper.getByInvitationCode(invitationCode, venueUniqueIdentifier);
                    byMembershipCardNumber.setCoachName(coachManagement.getCoachName());
                }
            }
            // 查询约课信息
            List<ActionListModel> reservationList = reservationMapper.selectListById(venueUniqueIdentifier, membershipCardNumber);
            Map<String, Object> result = new HashMap<>();
            if (byMembershipCardNumber != null) {
                MemberCardNumber memberCardNumber = memberUserManagementMapper.selectCardNumberByToday(venueUniqueIdentifier, membershipCardNumber);
                int cardNumber = memberCardNumber != null ? memberCardNumber.getCardNumber() : 0;
                // 使用反射获取对象的所有字段并放入 Map 中
                Field[] fields = byMembershipCardNumber.getClass().getDeclaredFields();
                for (Field field : fields) {
                    try {
                        field.setAccessible(true);
                        result.put(field.getName(), field.get(byMembershipCardNumber));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                // 将约课信息和卡片数量放入 Map 中
                result.put("reservationList", reservationList);
                result.put("cardNumber", cardNumber);
                // 返回 Map 对象
                return CommonResult.ok(result);
            } else {
                // 返回 Map 对象
                return CommonResult.ok(null);
            }
        }else {
            return CommonResult.ok("会员不存在");
        }

    }

    /**
     * @Author wx
     * @Description 查询入会人数
     * @Date 2023/12/27 20:33
     * @Return
     * @param venueUniqueIdentifier
     */
    @Override
    public CommonResult selectOnlineStatuss(String venueUniqueIdentifier) {
        List<MemberUserManagement> managementList = memberUserManagementMapper.selectOnlineStatuss(venueUniqueIdentifier);
        int i = 0;
        if (managementList.size()>0){
            i=managementList.size();
        }
        return CommonResult.ok(i);
    }

    /**
    * @Author 胡家浩
    * @Description 查询当天入场人数
    * @Date 2024/5/16 16:25
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param venueUniqueIdentifier
* @param currentDate
    */
    @Override
    public CommonResult selectEntranceNumber(String venueUniqueIdentifier, String currentDate) {
        List<MemberCardNumber> memberCardNumbersList = memberUserManagementMapper.selectEntranceNumber(venueUniqueIdentifier, currentDate);
        int count = 0;
        if (memberCardNumbersList.size() > 0){
            count = memberCardNumbersList.size();
        }
        return CommonResult.ok(count);
    }

    /**
     * @Author 胡家浩
     * @Description 根据卡号查询该用户当天是否入场
     * @Date 2024/5/16 20:48
     * @Return java.util.List<com.zhuiyun.project.api.memberTypeManagement.entity.MemberCardNumber>
     * @param memberCardNumber
     */
    @Override
    public CommonResult userIfEntrance(MemberCardNumber memberCardNumber) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(memberCardNumber.getUpdateTime());
            List<MemberCardNumber> memberCardNumberUser = memberUserManagementMapper.userIfEntrance(memberCardNumber.getVenueUniqueIdentifier(),memberCardNumber.getMembershipCardNumber(),formattedDate);
            //用户入场，更新刷卡时间
            if (memberCardNumberUser.size() > 0){
                int result = memberUserManagementMapper.userDepartureUpdate(memberCardNumber);
                return CommonResult.ok(result);
            } else {
                //未入场
                String venueUniqueIdentifier = memberCardNumber.getVenueUniqueIdentifier();
                String membershipCardNumber = memberCardNumber.getMembershipCardNumber();
                //查询用户会员卡类型
                MemberUserAndTypeModel memberUserAndTypeModel = memberUserManagementMapper.selectUserMemberType(venueUniqueIdentifier, membershipCardNumber);
                //关联表ID
                Integer id = memberUserAndTypeModel.getMemberUserId();
                //会员类型 （0 次数卡 / 1 期限卡）
                Integer memberType = memberUserAndTypeModel.getMemberType();
                //可用次数
                Integer availableTimes = memberUserAndTypeModel.getAvailableTimes();
                //过期时间
                Date expirationTime = memberUserAndTypeModel.getExpirationTime();
                if (memberType == 0){
                    if (availableTimes > 0){
                        //次数 -1
                        memberUserManagementMapper.deleteByMemberUserPhone(id);
                        //添加用户刷卡记录
                        int result = memberUserManagementMapper.userEntranceInsert(memberCardNumber);
                        return CommonResult.ok(result);
                    }else {
                        return CommonResult.ok("会员卡次数已用完");
                    }
                } else {
                    // 获取当前时间
                    long currentTime = System.currentTimeMillis();
                    if (expirationTime.getTime() < currentTime) {
                        System.out.println("已过期");
                        return CommonResult.ok("会员卡已过期");
                    } else if (expirationTime.getTime() == currentTime) {
                        return CommonResult.ok("会员卡已过期");
                    } else {
                        //添加用户刷卡记录
                        int result = memberUserManagementMapper.userEntranceInsert(memberCardNumber);
                        return CommonResult.ok(result);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.ok(0);
    }

    /**
     * @Author wx
     * @Description 会员离场
     * @Date 2023/12/28 8:16
     * @Return
     * @param id
     */
    @Override
    public CommonResult outVenuById(String venueUniqueIdentifier, Integer id) {
        return CommonResult.ok(memberUserManagementMapper.outVenuById(venueUniqueIdentifier,id));
    }

    /**
     * @Author wx
     * @Description 会员入场
     * @Date 2023/12/28 8:16
     * @Return
     * @param id
     */
    @Override
    public CommonResult intoVenuById(String venueUniqueIdentifier, Integer id) {
        // 创建一个事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 设置事务隔离级别
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 获取事务状态
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            // 调用第一个方法，并进行判断
            if (!method1(venueUniqueIdentifier,id)) {
                transactionManager.rollback(status); // 回滚事务
                return CommonResult.error(1, "第一个方法执行失败");
            }

            // 调用第二个方法，并进行判断
            if (!method2(venueUniqueIdentifier,id)) {
                transactionManager.rollback(status); // 回滚事务
                return CommonResult.error(1, "第二个方法执行失败");
            }

            // 所有方法执行成功，提交事务
            transactionManager.commit(status);
            return CommonResult.ok("所有方法执行成功");
        } catch (Exception e) {
            transactionManager.rollback(status); // 异常发生时回滚事务
            return CommonResult.error(1, e.getMessage());
        }
    }

    @Override
    public MemberUserManagement selectMemberByPhone(String phone) {

        return memberUserManagementMapper.selectMemberByPhone(phone);
    }

    @Override
    public void insertMemberUser(MemberUserManagement m) {
        memberUserManagementMapper.insertMemberUser(m);
    }

    @Override
    public CommonResult updateMemberInfoById(MemberUserAndTypeModel memberUserAndTypeModel) {
        memberUserAndTypeModel.setUpdateTime(new Date());
        return CommonResult.ok(memberUserManagementMapper.updateMemberInfoById(memberUserAndTypeModel));
    }

    @Override
    public CommonResult getMemberEntranceTimes(String venueUniqueIdentifier, String year, String month, String week) {
        List<MemberTypeManagementModel> memberEntranceTimes = memberUserManagementMapper.getMemberEntranceTimes(venueUniqueIdentifier, year, month, week);
        return CommonResult.ok(memberEntranceTimes);
    }

    /**
    * @Author 胡家浩
    * @Description 统计会员办卡情况(根据日期)
    * @Date 2024/5/21 17:08
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param venueUniqueIdentifier
    * @param year
    * @param month
    * @param week
    */
    @Override
    public CommonResult getMemberUserCardDate(String venueUniqueIdentifier, String year, String month, String week) {
        List<MemberTypeManagementModel> memberUserCardDate = memberUserManagementMapper.getMemberUserCardDate(venueUniqueIdentifier, year, month, week);
        return CommonResult.ok(memberUserCardDate);
    }

    /**
    * @Author wx
    * @Description 次数减一
    * @Date 2023/12/28 8:24
    * @Return
    */
    private boolean method1(String venueUniqueIdentifier,Integer id) {
        // 查询会员卡属性
        MemberTypeManagement memberTypeManagement = memberTypeMapper.selectType(venueUniqueIdentifier,id);
        if (memberTypeManagement !=null ){
            // 判断会员卡属于期限卡还是次卡
            if (memberTypeManagement.getMemberType()==0){
                MembershipRelationships membershipRelationships = membershipRelationshipsMapper.upTimes(id);
                if (membershipRelationships.getAvailableTimes()>0){
                    //执行减次数方法
                    int i = membershipRelationshipsMapper.reduceTimes(id);
                    if (i>0){
                        return true;
                    }else {
                        return false;
                    }
                }else {
                    return true;
                }
            }else {
                return true;
            }
        }else {
            return false;
        }
    }

    /**
    * @Author wx
    * @Description 入场次数加一及入场状态
    * @Date 2023/12/28 8:24
    * @Return
     */
    private boolean method2(String venueUniqueIdentifier, Integer id) {
        int i=memberUserManagementMapper.addOnlineTimes(venueUniqueIdentifier,id);
        if(i>0){
            return true;
        }else {
            // 方法逻辑，如果执行失败则返回 false
            return false;
        }

    }


}
